from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
# Create your views here.
from config.elastic.elasticSearchConfig import HOST, PORT
from work.models import Lable, Topic
from work.serializers import Lableserializers, Topicserializers
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination
from elasticsearch import Elasticsearch
from rest_framework.status import HTTP_204_NO_CONTENT,HTTP_404_NOT_FOUND


class TopicPaginationPageNumber(PageNumberPagination):
    page_size = 3#默认每页多少条数据
    page_size_query_param = 'size'#规定那个参数为分页大小参数
    max_page_size = 3#最大每页多少条数据

class TopicPaginationLimitOffset(LimitOffsetPagination):
    default_limit = 3  # 默认每页多少条
    max_limit = 100  # 最大每页多少条

class LableViewSet(ModelViewSet):
    queryset = Lable.objects.all()
    serializer_class = Lableserializers


en = Elasticsearch([{'host':HOST,'port':PORT}])
class TopicViewSet(ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = Topicserializers
    pagination_class = TopicPaginationPageNumber#使用分页器
    @action(["get"],detail=False)
    # detail的作用是声明action的路径是否与单一资源对应，True表示xxx/<pk>/action方法名，False表示xxx/action方法名
    # 将mysql的数据添加进elastic,这里应该是通过put方法来添加的，然后在调用对已有的数据不会重复添加
    def inites(self,request):
        serializer = self.get_serializer(self.get_queryset(),many=True)
        # 索引，指定id插入数据，body数据
        for i in serializer.data:
            en.index(index='topic',id=i['id'],body=i)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception = True)
        serializer.save()
        res_data = serializer.data
        #第一种方法
        # en.create(id=serializer['id'],index='topic',body=serializer.data)
        en.index(index='topic',id=res_data['id'],body=serializer.data)
        #第二种方法是调用inites
        # self.inites
        return ModelViewSet.create(self, request, *args, **kwargs)
    def update(self, request, *args, **kwargs):
        print(kwargs['pk'])
        try:
            topic = Topic.objects.get(pk=kwargs['pk'])
        except:
            return Response(status=HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(instance=topic,data=request.data)
        serializer.is_valid(raise_exception = True)
        serializer.save()
        data = {}
        data['doc'] = serializer.data
        # es的update方法，要把数据包括在doc里面，做成一个键值对的形式然后才可以，不然会报错
        en.update(id=kwargs['pk'],index='topic',body=data)
        return ModelViewSet.update(self, request, *args, **kwargs)
    def destroy(self, request, *args, **kwargs):
        # 这个是因为es和sql数据的id不符合出现的加减
        en.delete(id=str(int(kwargs['pk'])-1),index='topic')
        ModelViewSet.destroy(self, request, *args, **kwargs)
        return Response(status=HTTP_204_NO_CONTENT)
    @action(['get'],detail=False)
    def search(self,request):
        page = request.GET.get("page")
        query={
            "query": {
                'match': {
                }
            },
            "highlight": {
                "pre_tags": "<span style='color:red'>",
                "post_tags": "</span>",
                "fields": {
                    "subject": {}
                }
            },
            "from":(int(page)-1)*4,
            "size":4
        }
        if request.GET.get('subject'):
            query['query']['match'] = {"subject":request.GET.get('subject')}
        else:
            # 不给数据也没有必要再给全部数据，直接输出不存在就好了
            query['query']['match_all'] = {}
            return Response(query['query']['match_all'])
        es_res = en.search(index='topic',body=query)
        count = es_res["hits"]["total"]["value"]
        res = [self.hightlight(i) for i in es_res["hits"]["hits"]]
        #这个是自定义返回数据，所以在class上面定义的页码数，就不能起作用了
        #这里的分页需要使用哪一个elastic的功能去实现
        return Response({
            'msg':'ok',
            'count':count,
            'data':res
        })
    def hightlight(self,i):
        if i.get("highlight"):
            i["_source"]["subject"]=i['highlight']['subject'][0]
        return i['_source']






